package com.cn.springcloudshop.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cn.springcloudshop.common.AjaxRes;
import com.cn.springcloudshop.common.Const;
import com.cn.springcloudshop.common.DateUtils;
import com.cn.springcloudshop.model.*;
import com.cn.springcloudshop.service.impl.CatServiceImpl;
import com.cn.springcloudshop.service.inter.CatService;
import com.cn.springcloudshop.service.inter.ProductService;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @Author: wuyanzu
 * @Date: 2018/7/30
 */
@RestController
@RequestMapping("/product/")
public class ProductController {
    
    @Autowired
    ProductService productService;

    @Autowired
    CatService catService;

    /**
    *
    * 根据排序字段查询前5条商品信息用于轮播展示
    * @author wuyanzu
    * @date 2018/8/15 14:27
    * @param [ajaxRes]
    * @return com.cn.springcloudshop.common.AjaxRes
    */
    @RequestMapping("Carousel")
    public AjaxRes getCarouselProduct(AjaxRes ajaxRes) {
        YmShopProductExample ymShopProductExample = new YmShopProductExample();
        ymShopProductExample.setOrderByClause("sort_order asc");
        ymShopProductExample.setDistinct(true);
        //ymShopProductExample.setLimit(0);
        ymShopProductExample.setOffset(4);
        ymShopProductExample.createCriteria().andStateEqualTo(1L).andOndateLessThanOrEqualTo(new Date()).
                andOffdateGreaterThan(new Date());
        List<YmShopProduct> list = productService.selectByExample(ymShopProductExample);
        if (list != null && list.size() > 0) {
            ajaxRes.setSucceed(list, Const.DATA_SUCCEED);
        } else {
            ajaxRes.setSucceedMsg("暂无商品");
        }
        return ajaxRes;
    }

    /**
    *
    * 根据类目id查询商品信息
    * @author wuyanzu
    * @date 2018/8/14 14:21
    * @param [ajaxRes, catId]
    * @return com.cn.springcloudshop.common.AjaxRes
    */
    @RequestMapping("getByCatId")
    public AjaxRes getProductByCatId(AjaxRes ajaxRes,Long catId){
        if (catId != null) {
            YmShopProductExample ymShopProductExample = new YmShopProductExample();
            ymShopProductExample.setOrderByClause("sort_order asc");
            ymShopProductExample.createCriteria().andCatIdEqualTo(catId);
            List<YmShopProduct> list = productService.selectByExample(ymShopProductExample);
            if (list != null && list.size() > 0) {
                ajaxRes.setSucceed(list, Const.DATA_SUCCEED);
            } else {
                ajaxRes.setSucceedMsg("暂无商品");
            }
        } else {
            ajaxRes.setFailMsg(Const.PARAMETER_NULL);
        }
        return ajaxRes;
    }

    /**
    *
    * 更新商品图片信息
    * @author wuyanzu
    * @date 2018/8/14 14:22
    * @param [ajaxRes, productId, picPath, detPicPath]
    * @return com.cn.springcloudshop.common.AjaxRes
    */
    @RequestMapping("updatePic")
    public AjaxRes updatePic(AjaxRes ajaxRes,Long productId,String picPath,String detPicPath) {
        if (productId != null && StringUtils.isNotEmpty(picPath) && StringUtils.isNotEmpty(detPicPath)) {
            YmShopProduct ymShopProduct = productService.selectByPrimaryKey(productId);
            if (ymShopProduct != null) {
                ymShopProduct.setProductPic(picPath);
                ymShopProduct.setProductDetailsPic(detPicPath);
                if (productService.updateByPrimaryKeySelective(ymShopProduct) == 1) {
                    ajaxRes.setSucceedMsg(Const.UPDATE_SUCCEED);
                } else {
                    ajaxRes.setFailMsg(Const.UPDATE_FAIL);
                }
            } else {
                ajaxRes.setFailMsg("未知商品");
            }
        } else {
            ajaxRes.setFailMsg("参数不全");
        }
        return ajaxRes;
    }
    /**
    * 添加商品
    * @author wuyanzu 
    * @date 2018/7/30 17:10
    * @param [product]
    * @return int
    */
    @RequestMapping("add")
    public AjaxRes insertProduct(String product, AjaxRes ajaxRes) {
        if (!StringUtils.isNotEmpty(product)) {
            ajaxRes.setFailMsg("商品不能为空");
        }
        YmShopProduct ymShopProduct = JSONObject.parseObject(product, YmShopProduct.class);
        if (productService.insert(ymShopProduct) == 1) {
            ajaxRes.setSucceed(ymShopProduct.getProductId(),Const.SAVE_SUCCEED);
        } else {
            ajaxRes.setFailMsg(Const.SAVE_FAIL);
        }
        return ajaxRes;
    }
    
    /**
    * 根据主键查询商品信息
    * @author wuyanzu 
    * @date 2018/7/30 17:10
    * @param [productId]
    * @return com.cn.springcloudshop.model.YmShopProduct
    */
    @RequestMapping("getByPK")
    public AjaxRes getProductByPK(Long productId,AjaxRes ajaxRes) {
        YmShopProduct product = productService.selectByPrimaryKey(productId);
        if (product != null) {
            ajaxRes.setSucceed(product,Const.DATA_SUCCEED);
        } else {
            ajaxRes.setFailMsg(Const.DATA_FAIL);
        }
        return ajaxRes;
    }
    
    /**
    * 更新商品信息
    * @author wuyanzu 
    * @date 2018/7/30 17:10
    * @param [product]
    * @return int
    */
    @RequestMapping("update")
    public AjaxRes updateProduct(String product,AjaxRes ajaxRes) {
        if (!StringUtils.isNotEmpty(product)) {
            ajaxRes.setFailMsg("商品不能为空");
        }
        YmShopProduct ymShopProduct = JSONObject.parseObject(product, YmShopProduct.class);
        if (productService.updateByPrimaryKeySelective(ymShopProduct) == 1) {
            ajaxRes.setSucceedMsg(Const.UPDATE_SUCCEED);
        } else {
            ajaxRes.setFailMsg(Const.UPDATE_FAIL);
        }
        return ajaxRes;
    }

    /**
    * 删除商品
    * @author wuyanzu 
    * @date 2018/7/30 17:16
    * @param [productId]
    * @return int
    */
    @RequestMapping("del")
    public AjaxRes delProductByPK(Long productId,AjaxRes ajaxRes) {
        if (productService.deleteByPrimaryKey(productId) == 1) {
            ajaxRes.setSucceedMsg(Const.DEL_SUCCEED);
        } else {
            ajaxRes.setFailMsg(Const.DEL_FAIL);
        }
        return ajaxRes;
    }

    /**
    *
    * @author wuyanzu
    * @date 2018/7/30 17:11
    * @param []
    * @return java.util.List<com.cn.springcloudshop.model.YmShopProduct>
    */
    @RequestMapping("getAll")
    public AjaxRes getAllProduct(AjaxRes ajaxRes,int pageNumber) {
        int pageSize = 10;
        YmShopProductExample ymShopProductExample = new YmShopProductExample();
        ymShopProductExample.setOrderByClause("sort_order asc");
        ymShopProductExample.setDistinct(true);
        ymShopProductExample.createCriteria().andStateEqualTo(1L).andOndateLessThanOrEqualTo(new Date()).
                andOffdateGreaterThan(new Date());
        if (pageNumber == 1) {
            ymShopProductExample.setLimit(0);
            ymShopProductExample.setOffset(pageSize);
        } else {
            ymShopProductExample.setLimit((pageNumber - 1) * pageSize);
            ymShopProductExample.setOffset(pageSize);
        }

        List<YmShopProduct> list = productService.selectByExample(ymShopProductExample);
        if (list != null && list.size() > 0) {
            ajaxRes.setSucceed(list, Const.DATA_SUCCEED);
        } else {
            ajaxRes.setFailMsg(Const.DATA_FAIL);
        }
        return ajaxRes;
    }

    /**
    * 商品分页条件查询
    * @author wuyanzu 
    * @date 2018/7/30 18:40
    * @param [state, type, onDate, offDate, page]
    * @return java.util.List<com.cn.springcloudshop.model.YmShopProduct>
    */
    @RequestMapping("conditionalQuery")
    public AjaxRes selectByExample(AjaxRes ajaxRes,@RequestParam(required = false) Long id,@RequestParam(required = false) Long state,@RequestParam(required = false) String type,
        @RequestParam(required = false) Date onDate,@RequestParam(required = false) Date offDate,
        @RequestParam(required = false)Integer pageNum,@RequestParam(required = false)Integer pageSize){
        YmShopProductExample ymShopProductExample = new YmShopProductExample();
        YmShopProductExample.Criteria criteria = ymShopProductExample.createCriteria();
        if (id != null && id != 0) {
            criteria.andProductIdEqualTo(id);
        }
        if (state != null) {
            criteria.andStateEqualTo(state);
        }
        if (!"".equals(type) && type != null) {
            criteria.andProductTypeEqualTo(type);
        }
        if (onDate != null) {
            criteria.andOndateGreaterThan(onDate);
        }
        if (offDate != null) {
            criteria.andOffdateLessThan(offDate);
        }
        //List<YmShopProduct> list = productService.selectByExample(ymShopProductExample);
        int size = productService.countByExample(ymShopProductExample);
        int totalPage = 1;
        if (size % pageSize == 0) {
            totalPage = size / pageSize;
        } else {
            totalPage = size / pageSize + 1;
        }

        if (pageNum != null) {
            if (size > pageSize) {
                ymShopProductExample.setLimit((pageNum - 1) * pageSize);
            } else {
                ymShopProductExample.setLimit(0);
            }
            ymShopProductExample.setOffset(pageSize);
        } else {
            ymShopProductExample.setLimit(0);
            ymShopProductExample.setOffset(pageSize);
        }
        ymShopProductExample.setOrderByClause("ondate desc");
        List<YmShopProduct> list = productService.selectByExample(ymShopProductExample);
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setName(catService.selectByPrimaryKey(list.get(i).getCatId()).getText());
            if (list.get(i).getCreateTime() != null) {
                list.get(i).setCrTimeString(DateUtils.formatDate(list.get(i).getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
            }
            if (list.get(i).getUpdateTime() != null) {
                list.get(i).setUpTimeString(DateUtils.formatDate(list.get(i).getUpdateTime(),"yyyy-MM-dd HH:mm:ss"));
            }
            if (list.get(i).getOffdate() != null) {
                list.get(i).setOffTimeString(DateUtils.formatDate(list.get(i).getOffdate(),"yyyy-MM-dd HH:mm:ss"));
            }
            if (list.get(i).getOndate() != null) {
                list.get(i).setOnTimeString(DateUtils.formatDate(list.get(i).getOndate(),"yyyy-MM-dd HH:mm:ss"));
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        map.put("totalPage", totalPage);
        map.put("totalRecord", size);
        if (list != null && list.size() > 0) {
            map.put("list", list);
            ajaxRes.setSucceed(map, Const.DATA_SUCCEED);
        } else {
            map.put("list", null);
            ajaxRes.setSucceed(map,Const.DATA_SUCCEED);
        }
        return ajaxRes;
    }

    /**
    *
    * 批量修改商品信息
    * @author wuyanzu
    * @date 2018/8/14 14:24
    * @param [products, ajaxRes]
    * @return com.cn.springcloudshop.common.AjaxRes
    */
    @RequestMapping("updateBatch")
    public AjaxRes updateBatchByPK(String products, AjaxRes ajaxRes) {
        if (StringUtils.isNotEmpty(products)) {
            JSONObject jsonObject = JSONObject.parseObject(products);
            Long state = jsonObject.getLong("state");
            JSONArray jsonArray = jsonObject.getJSONArray("products");
            List<YmShopProduct> list = new ArrayList<>();
            list = jsonArray.toJavaList(YmShopProduct.class);
            System.err.println(list.size());
            if (products == null) {
                ajaxRes.setFailMsg("商品参数为空");
                return ajaxRes;
            }
            if (state != null) {
                for (int i = 0; i < list.size(); i++) {
                    list.get(i).setState(state);
                }
            }
            if (productService.updateBatchByPK(list) != 0) {
                ajaxRes.setSucceedMsg(Const.UPDATE_SUCCEED);
            } else {
                ajaxRes.setFailMsg(Const.UPDATE_FAIL);
            }
        } else {
            ajaxRes.setFailMsg("参数不能为空");
        }
        return ajaxRes;
    }

   /* @RequestMapping("testAdd")
    public int addPro() {
        YmShopProduct ymShopProduct = new YmShopProduct();
        ymShopProduct.setCreateTime(new Date());
        ymShopProduct.setProductName("测试2");
        ymShopProduct.setState(1L);
        return productService.insertSelective(ymShopProduct);
    }*/
}
